package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mvc.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;


    /**
     * 我的优惠券列表
     * @param status
     * @param lastId
     * @return
     */
    @Override
    public List<CouponInfoResDTO> myCoupon(Integer status, Long lastId) {
        Long userId = UserContext.currentUserId();
        List<Coupon> list = this.lambdaQuery().eq(Coupon::getUserId, userId)
                .eq(Coupon::getStatus, status)
                .eq(ObjectUtils.isNotEmpty(lastId), Coupon::getId, lastId).list();
        if (CollUtils.isEmpty(list)){
            throw new CommonException("没有优惠券");
        }
        List<CouponInfoResDTO> collect = list.stream().map(s -> {
            CouponInfoResDTO bean = BeanUtils.toBean(s, CouponInfoResDTO.class);
            return bean;
        }).collect(Collectors.toList());
        if (CollUtils.isEmpty(collect)){
            throw new CommonException("没有优惠券");
        }
        return collect;
    }
}
